﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.ComponentModel.Composition.Hosting;

namespace UnfriendlyFire
{
    public class MefControllerFactory : DefaultControllerFactory
    {
        private CompositionContainer _container;

        public MefControllerFactory()
        {
            _container = new CompositionContainer(new AssemblyCatalog(typeof(MefControllerFactory).Assembly));
        }

        public override IController CreateController(RequestContext requestContext, string controllerName)
        {
            var controllers = _container.GetExports<IController, IControllerMetadataView>();
            var controller = controllers.Where(c => c.Metadata.Name == controllerName).FirstOrDefault();
            if (controller != null)
            {
                return controller.Value;
            }
            return base.CreateController(requestContext, controllerName);
        }
    }
}